<template>
  <a-modal
    :title="id ? $t('all.autotext1722') : $t('all.autotext1717')"
    :visible="visible"
    width="760px"
    :okText="$t('all.autotext218')"
    :canceltext="$t('all.autotext975')"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="formRef"
      :model="form"
      v-bind="formItemLayout"
      :rules="formRules"
    >
      <a-form-model-item :label="$t('all.autotext1718')" prop="businessCode">
        <a-input
          v-model="form.businessCode"
          :disabled="existFeeApply"
          @change="handleBusinessCodeChange"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1719')" prop="sponsorId">
        <a-select
          v-model="form.sponsorId"
          show-search
          :filter-option="filterOption"
          :disabled="Boolean(id)"
        >
          <a-select-option v-for="list in phaseList" :key="list.id">
            {{ list.orgName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1789')" prop="customerId">
        <a-select
          v-model="form.customerId"
          show-search
          :filter-option="filterOption"
          :disabled="Boolean(id) && Boolean(record.customerId)"
        >
          <a-select-option v-for="list in phaseList" :key="list.id">
            {{ list.orgName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1790')" prop="contractAmount">
        <a-input-number
          :min="0"
          style="width: 100%"
          :precision="2"
          v-model="form.contractAmount"
        />
      </a-form-model-item>

      <a-form-model-item :label="$t('all.autotext1829')" prop="advancedPay">
        <a-radio-group :disabled="Boolean(id)" v-model="form.advancedPay">
          <a-radio :value="1">{{ $t('all.autotext1830') }}</a-radio>
          <a-radio :value="0">{{ $t('all.autotext1831') }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1832')" prop="cashFlowType">
        <!-- :disabled="Boolean(id)" 新增需求编辑时可修改 -->
        <!-- 二次需求变更，编辑时判断是否入账决定是否更改 -->
        <a-radio-group
          :disabled="!allowModify"
          v-model="form.cashFlowType"
        >
          <a-radio :value="0">{{ $t('all.autotext1833') }}</a-radio>
          <a-radio :value="1">{{ $t('all.autotext1834') }}</a-radio>
        </a-radio-group>
      </a-form-model-item>

      <!--      <a-form-model-item
        v-for="(item, i) in form.contractCode"
        :key="i"
        :prop="'contractCode.' + i + '.value'"
        v-bind="i === 0 ? {} : wrapperColOffset"
        :label="i === 0 ? $t('all.autotext46') : ''"
        :rules="[
          { required: true, message: $t('all.autotext327'), trigger: 'blur' },
          { validator: validatePassCode, trigger: 'blur' }
        ]"
      >
        <a-input v-model="item.value" style="width: 80%;" @change="handleContractCodeChange(item, i)" />
        <a-icon
          v-if="form.contractCode.length > 1"
          class="dynamic-delete-button"
          type="minus-circle-o"
          @click="removeDomain(item, i)"
        />
        <div class="warn" v-if="item.check">
          <a-icon class="warn-icon" type="exclamation-circle" theme="filled" />
          {{ $t('all.autotext1770') }}
          <a-button type="link" @click="warnDetail(item)">{{ $t('all.autotext475.1') }}</a-button>
        </div>
      </a-form-model-item>
      <a-form-model-item v-bind="wrapperColOffset">
        <a-button type="dashed" style="width: 60%" @click="addDomain">
          <a-icon type="plus" /> {{ $t('all.autotext1766') }}
        </a-button>
      </a-form-model-item>-->
      <a-form-model-item :label="$t('all.autotext1724')">
        <a-upload
          accept=".pdf, .jpg, .jpeg, .png"
          :file-list="icfList"
          action="/api/common/upload"
          @change="e => handleChange(e, 1)"
        >
          <a-button type="primary">{{ $t('all.autotext565') }}</a-button>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1725')">
        <a-upload
          accept=".pdf, .jpg, .jpeg, .png"
          :file-list="ethicsList"
          action="/api/common/upload"
          @change="e => handleChange(e, 2)"
        >
          <a-button type="primary">{{ $t('all.autotext565') }}</a-button>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1726')">
        <a-upload
          accept=".pdf, .jpg, .jpeg, .png"
          :file-list="authorizList"
          action="/api/common/upload"
          @change="e => handleChange(e, 3)"
        >
          <a-button type="primary">{{ $t('all.autotext565') }}</a-button>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1727')">
        <a-upload
          accept=".pdf, .jpg, .jpeg, .png"
          :file-list="notesList"
          action="/api/common/upload"
          @change="e => handleChange(e, 4)"
        >
          <a-button type="primary">{{ $t('all.autotext565') }}</a-button>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1728')">
        <a-textarea
          v-model="form.notes"
          :auto-size="{ minRows: 2, maxRows: 6 }"
        />
      </a-form-model-item>
    </a-form-model>
    <warnDetail ref="warnRef" />
  </a-modal>
</template>

<script>
import {
  busNumberSave,
  busNumberUpdate,
  getProByContractCode,
  checkContractCashFlow,
  existFeeApplyByBusinessCode
} from '@/api/entry/entry'
import { getSponsorList } from '@api/system/user'
import warnDetail from './warnDetail'

export default {
  components: { warnDetail },
  data () {
    return {
      id: '',
      visible: false,
      allowModify: false, // 入账方式是否允许修改，为true可修改
      record: {},
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 }
      },
      wrapperColOffset: {
        wrapperCol: { span: 15, offset: 5 }
      },
      phaseList: [],
      form: {
        businessCode: '',
        sponsorId: '',
        customerId: '',
        contractAmount: '',
        advancedPay: '', // 1 表示垫付 0 表示非垫付
        cashFlowType: '', // 0 合同入账 1 临床试验入账

        // contractCode: [
        //   {
        //     value: ''
        //   }
        // ],
        notes: ''
      },
      formRules: {
        businessCode: [
          {
            required: true,
            message: this.$t('all.autotext1723'),
            trigger: 'blur'
          },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        sponsorId: [
          {
            required: true,
            message: this.$t('all.autotext1749'),
            trigger: 'change'
          }
        ],
        customerId: [
          {
            required: true,
            message: this.$t('all.autotext1791'),
            trigger: 'change'
          }
        ],
        contractAmount: [
          {
            required: true,
            message: this.$t('all.autotext1792'),
            trigger: 'blur'
          }
        ],
        advancedPay: [
          {
            required: true,
            message: this.$t('all.autotext1835'),
            trigger: 'blur'
          }
        ],
        cashFlowType: [
          {
            required: true,
            message: this.$t('all.autotext1836'),
            trigger: 'blur'
          }
        ]
      },
      icfList: [],
      ethicsList: [],
      authorizList: [],
      notesList: [],
      oldContractCode: [],
      hasApply: false,
      existFeeApply: false
    }
  },
  mounted () {
    this.getSponsorList()
  },
  methods: {
    async open (record) {
      if (record) {
        this.record = record
        this.id = record.id
        this.form.businessCode = record.businessCode
        this.form.sponsorId = record.sponsorId
        this.form.customerId = record.customerId
        this.form.contractAmount = record.contractAmount
        this.form.advancedPay = record.advancedPay || 0
        this.form.cashFlowType = record.cashFlowType || 0

        const res = await existFeeApplyByBusinessCode({
          businessCode: record.businessCode,
          classify: this.$store.state.user.classify
        })
        this.existFeeApply = res

        // this.oldContractCode = record.contractCode?.split(',')
        // this.form.contractCode = record.contractCode?.split(',').map(item => {
        //   return {
        //     value: item
        //   }
        // })
        this.form.notes = record.notes
        // eslint-disable-next-line multiline-ternary
        this.icfList = record.icf
          ? JSON.parse(record.icf).map((item, i) => {
              return {
                uid: i + 1,
                name: item.name,
                url: this.$options.filters.dealImageUrl(item.url),
                response: {
                  data: item.url
                }
              }
            })
          : []
        // eslint-disable-next-line multiline-ternary
        this.ethicsList = record.ethics
          ? JSON.parse(record.ethics).map((item, i) => {
              return {
                uid: i + 1,
                name: item.name,
                url: this.$options.filters.dealImageUrl(item.url),
                response: {
                  data: item.url
                }
              }
            })
          : []
        // eslint-disable-next-line multiline-ternary
        this.authorizList = record.authorizeEntrust
          ? JSON.parse(record.authorizeEntrust).map((item, i) => {
              return {
                uid: i + 1,
                name: item.name,
                url: this.$options.filters.dealImageUrl(item.url),
                response: {
                  data: item.url
                }
              }
            })
          : []
        // eslint-disable-next-line multiline-ternary
        this.notesList = record.file
          ? JSON.parse(record.file).map((item, i) => {
              return {
                uid: i + 1,
                name: item.name,
                url: this.$options.filters.dealImageUrl(item.url),
                response: {
                  data: item.url
                }
              }
            })
          : []

        checkContractCashFlow({ businessCode: record.businessCode }).then(
          allowModify => {
            this.allowModify = allowModify
          }
        )
      } else {
        this.form = {
          businessCode: '',
          sponsorId: '',
          customerId: '',
          contractAmount: '',
          advancedPay: '',
          cashFlowType: '',

          // contractCode: [
          //   {
          //     value: ''
          //   }
          // ],
          notes: ''
        }
        this.existFeeApply = false
      }
      this.allowModify = true
      this.visible = true
    },
    // 请求申办方列表
    getSponsorList () {
      getSponsorList({ code: 10001011 }).then(res => {
        this.phaseList = res
      })
    },
    handleChange ({ fileList }, type) {
      const fileArr = fileList.map(item => {
        return {
          ...item,
          url: this.$options.filters.dealImageUrl(item.response?.data)
        }
      })
      let file = fileArr.length ? [fileArr[fileArr.length - 1]] : []
      switch (type) {
        case 1:
          this.icfList = file
          break
        case 2:
          this.ethicsList = file
          break
        case 3:
          this.authorizList = file
          break
        case 4:
          this.notesList = fileArr
          break
      }
    },
    handleOk () {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        // const check = this.form.contractCode.findIndex(item => item.check)
        // if (check !== -1) return
        const that = this

        this.$confirm({
          title: this.$t('all.autotext1729'),
          content: this.$t('all.autotext1730'),
          onOk: async () => {
            let icfFile = that.icfList.map(item => {
              return {
                name: item.name,
                url: item.response?.data
              }
            })
            let ethicsFile = that.ethicsList.map(item => {
              return {
                name: item.name,
                url: item.response?.data
              }
            })
            let authorizeFile = that.authorizList.map(item => {
              return {
                name: item.name,
                url: item.response?.data
              }
            })
            let notesFile = that.notesList.map(item => {
              return {
                name: item.name,
                url: item.response?.data
              }
            })
            let params = {
              id: this.id,
              ...that.form,
              // contractCode: that.form.contractCode.map(item => item.value).join(','),
              icf: JSON.stringify(icfFile),
              ethics: JSON.stringify(ethicsFile),
              authorizeEntrust: JSON.stringify(authorizeFile),
              file: JSON.stringify(notesFile)
            }

            if (this.id) {
              await busNumberUpdate(params, { id: this.id })
            } else {
              await busNumberSave(params)
            }
            this.$emit('refresh')
            this.handleCancel()
          }
        })
      })
    },
    handleCancel () {
      this.id = ''
      this.icfList = []
      this.ethicsList = []
      this.authorizList = []
      this.notesList = []
      this.$refs.formRef.resetFields()
      this.oldContractCode = []
      this.visible = false
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    async removeDomain (item, index) {
      if (!this.oldContractCode[index]) {
        this.form.contractCode.splice(index, 1)
        return
      }
      const res = await getProByContractCode({
        contractCode: this.oldContractCode[index],
        classify: this.$store.state.user.classify
      })
      if (res.length) {
        this.$set(this.form.contractCode[index], 'check', true)
        this.$set(this.form.contractCode[index], 'info', res)
      } else {
        this.form.contractCode.splice(index, 1)
      }
    },
    addDomain () {
      this.form.contractCode.push({
        value: ''
      })
    },
    validatePass (rule, value, callback) {
      if (/\s/.test(value)) {
        callback(new Error(this.$t('all.autotext711')))
      } else {
        callback()
      }
    },
    async validatePassCode (rule, value, callback) {
      const index = rule.field.split('.')[1]
      if (!value) {
        callback(new Error(this.$t('all.autotext327')))
      } else if (/\s/.test(value)) {
        callback(new Error(this.$t('all.autotext711')))
      } else {
        if (
          this.oldContractCode[index] &&
          this.oldContractCode[index] !== value
        ) {
          const res = await getProByContractCode({
            contractCode: this.oldContractCode[index],
            classify: this.$store.state.user.classify
          })
          if (res.length) {
            this.$set(this.form.contractCode[index], 'check', true)
            this.$set(this.form.contractCode[index], 'info', res)
          } else {
            this.$set(this.form.contractCode[index], 'check', false)
            this.$set(this.form.contractCode[index], 'info', [])
          }
        } else {
          this.$set(this.form.contractCode[index], 'check', false)
          this.$set(this.form.contractCode[index], 'info', [])
        }
        callback()
      }
    },
    warnDetail (item) {
      if (!item.info) return
      this.$refs.warnRef.open(item.info, 2)
    },
    handleBusinessCodeChange () {
      // eslint-disable-next-line no-useless-escape
      this.form.businessCode = this.form.businessCode.replace(
        /[^\a-\z\A-\Z0-9\_\.]/g,
        ''
      )
    },
    handleContractCodeChange (item, i) {
      // eslint-disable-next-line no-useless-escape
      item.value = item.value.replace(/[^\a-\z\A-\Z0-9\_\.]/g, '')
    }
  }
}
</script>

<style lang="less" scoped>
.icon {
  font-size: 16px;
  padding-left: 10px;
}
/deep/.ant-form-item-label {
  margin: 0;
}
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  left: 10px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.warn {
  padding: 0 0 0 20px;
  border-radius: 2px;
  background: #ecf0f7;
  .warn-icon {
    color: #f79925;
    font-size: 16px;
    margin-right: 10px;
  }
}
</style>
